package com.dlut.preparedStatement.crud;

import com.dlut.bean.Customer;
import com.dlut3.util.JDBCUtil;
import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;
import java.sql.*;

/**
 * 针对Customers表的查询操作
 */
public class CustomerForQuery {




    @Test
    public void test2(){
        String sql = "select id,name,birth from customers where id = ?";
        Customer customer = queryForCustomer(sql, 13);
        System.out.println(customer);

        sql = "select id,email,name,birth from customers where name = ?";
        customer = queryForCustomer(sql, "周杰伦");
        System.out.println(customer);
    }

    /**
     * 通用的查询操作
     * @param sql sql语句
     * @param args 语句的参数
     * @return customer类
     */
    public Customer queryForCustomer(String sql, Object ...args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtil.getConnection();

            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i+1, args[i]);
            }
            rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            Customer customer;
            if (rs.next()){
                customer = new Customer();
                for (int i = 0; i < columnCount; i++) {
                    Object columnValue = rs.getObject(i + 1);
                    String columnName = rsmd.getColumnName(i + 1);
                    Field field = Customer.class.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(customer,columnValue);
                }
                return customer;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeResource(conn,ps,rs);
        }
        return null;
    }

    @Test
    public void test1Query(){
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = "select id,name,email,birth from customers where id = ?";
            ps = conn.prepareStatement(sql);
            ps.setObject(1,4);

            resultSet = ps.executeQuery();
            //处理结果集
            if (resultSet.next()){
                //
                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String email = resultSet.getString(3);
                Date birth = resultSet.getDate(4);

                //数据封装为一个对象
                Customer customer = new Customer(id, name, email, birth);
                System.out.println(customer);

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.closeResource(conn, ps, resultSet);
        }


    }
}
